import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../domain/entities/user.dart';
import 'dependencies.dart';

/// Web专用认证状态
abstract class AuthStateWeb {}

class AuthInitialWeb extends AuthStateWeb {}

class AuthLoadingWeb extends AuthStateWeb {}

class AuthSuccessWeb extends AuthStateWeb {
  final User user;
  AuthSuccessWeb(this.user);
}

class AuthErrorWeb extends AuthStateWeb {
  final String message;
  AuthErrorWeb(this.message);
}

/// Web专用认证状态通知器（仅支持在线功能）
class AuthStateNotifierWeb extends Notifier<AuthStateWeb> {
  late final Ref _ref;

  @override
  AuthStateWeb build() {
    _ref = ref;
    return AuthInitialWeb();
  }

  /// 登录（Web端仅支持在线登录）
  Future<void> login(String username, String password) async {
    state = AuthLoadingWeb();

    try {
      final authUseCases = _ref.read(authUseCasesProvider);
      final result = await authUseCases.login(
        username: username,
        password: password,
      );

      if (result.isSuccess && result.data != null) {
        // 将LoginResponse中的UserInfo转换为User实体
        final userInfo = result.data!.user;
        final user = User(
          id: userInfo.id,
          username: userInfo.username,
          email: userInfo.email,
          role: userInfo.role,
          orgName: userInfo.orgName,
          avatarUrl: userInfo.avatarUrl,
        );
        state = AuthSuccessWeb(user);
      } else {
        state = AuthErrorWeb(result.errorMessage ?? '登录失败');
      }
    } catch (e) {
      // 提供更详细的错误信息
      String errorMessage = '登录失败';
      if (e.toString().contains('401')) {
        errorMessage = '用户名或密码错误';
      } else {
        errorMessage = '登录失败：${e.toString()}';
      }
      state = AuthErrorWeb(errorMessage);
    }
  }

  /// 登出
  Future<void> logout({bool clearLocalData = true}) async {
    try {
      final authUseCases = _ref.read(authUseCasesProvider);
      await authUseCases.logout(clearLocalData: clearLocalData);
      state = AuthInitialWeb();
    } catch (e) {
      state = AuthErrorWeb('登出失败：${e.toString()}');
    }
  }

  /// 检查登录状态（Web端仅支持在线检查）
  Future<void> checkAuthStatus() async {
    try {
      final authUseCases = _ref.read(authUseCasesProvider);

      // 在线模式：从服务器获取用户信息
      final result = await authUseCases.getCurrentUser();

      if (result.isSuccess && result.data != null) {
        final userInfo = result.data!;
        final user = User(
          id: userInfo.id,
          username: userInfo.username,
          email: userInfo.email,
          role: userInfo.role,
          orgName: userInfo.orgName,
          avatarUrl: userInfo.avatarUrl,
        );
        state = AuthSuccessWeb(user);
      } else {
        state = AuthInitialWeb();
      }
    } catch (e) {
      state = AuthInitialWeb();
    }
  }
}

/// Web专用认证状态Provider
final authStateProviderWeb =
    NotifierProvider<AuthStateNotifierWeb, AuthStateWeb>(
        AuthStateNotifierWeb.new);

/// Web专用当前用户Provider
final currentUserProviderWeb = Provider<User?>((ref) {
  final authState = ref.watch(authStateProviderWeb);
  return authState is AuthSuccessWeb ? authState.user : null;
});

/// Web专用是否已登录Provider
final isLoggedInProviderWeb = Provider<bool>((ref) {
  final authState = ref.watch(authStateProviderWeb);
  return authState is AuthSuccessWeb;
});
